<template>
    <div class="app-container">
        <div class="customContainer" v-if="tab_view==1">
            <div class="store">
                <el-form size="small" :inline="true">
                    <el-form-item>
                        <el-select
                                placeholder="选择门店"
                                v-model="formInline.store_id"
                                @change="listArray"
                                style="width:250px"
                                filterable>
                            <el-option
                                    v-for="item in store_list"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-button class="pull-right" type="primary" size="small" @click="addTypeClick()">添加方案</el-button>
                </el-form>
            </div>
            <!-- 搜索头 -->
            <el-form :inline="true" :model="formInline" size="small">
                <el-form-item>
                    <span style="color: #888;">状态：</span>
                    <el-select
                            v-model="formInline.status"
                            style="width: 150px"
                            placeholder="请选择">
                        <el-option
                                v-for="item in state_list"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-input style="width: 200px" v-model="formInline.name" placeholder="请输入名称" @keyup.enter.native="listArray">
                    </el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="listArray">搜索</el-button>
                </el-form-item>
            </el-form>

            <el-table highlight-current-row :data="list" border size="mini" v-loading.body="listLoading">
                <el-table-column align="center" label='序号' width="50">
                    <template slot-scope="scope">{{scope.$index+1+(currentPage-1)*20}}</template>
                </el-table-column>
                <el-table-column align="center" label="方案名称" prop="name"></el-table-column>
                <el-table-column align="center" label="最多累计次数" width="100px">
                    <template slot-scope="scope">{{scope.row.times}}次</template>
                </el-table-column>
                <el-table-column align="center" label="状态" width="100px">
                    <template slot-scope="scope">{{scope.row.status==1?"已启用":"已停用"}}</template>
                </el-table-column>
                <el-table-column align="center" label='操作' width="330">
                    <template slot-scope="scope">
                        <el-button  type="primary" plain size="mini" @click="signEnables(scope.row)">{{scope.row.status==1?'停用':'启用'}}</el-button>
                        <el-button  type="primary" plain size="mini" @click="details(scope.row)">详情</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 新建-->
        <div v-show="tab_view==2" class="customContainer">
            <el-button class="pull-left" type="primary" size="small" @click="backClick">返 回</el-button>
            <div class="tab_title">{{top_title}}</div>
            <el-form
                    :model="infoForm"
                    ref="infoForm"
                    :disabled="isDisabled"
            >
                <el-form-item label="方案名称">
                    <el-input style="width: 280px" v-model="infoForm.name" placeholder="请输入方案名称"  maxlength="15" show-word-limit></el-input>
                </el-form-item>
                <el-table stripe highlight-current-row :data="selectList" border size="mini" class="table">
                    <el-table-column align="center" label='选择' width="50">
                        <template slot-scope="scope">
                            <el-radio v-model="distributionRadio" :label="scope.$index+1" :disabled="isDisabled"><em></em></el-radio>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="累计签到" prop="lable"></el-table-column>
                    <el-table-column align="center" label="商品名称" prop="name"></el-table-column>
                    <el-table-column align="center" label="类型" prop="type_name"></el-table-column>
                    <el-table-column align="center" label="有效期" prop="time"></el-table-column>
                    <el-table-column align="center" label="更新时间" prop="update_time"></el-table-column>
                    <el-table-column align="center" label='操作'>
                        <template slot-scope="scope">
                            <el-button :disabled="isDisabled" type="danger" size="mini" @click="delRelevance(scope.$index)">移除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="op_title" >选择商品/券</div>
                <el-form :inline="true" :model="relevanceFrom" ref="relevanceForm" size="small" :disabled="isDisabled">
                    <el-form-item>
                        <el-select
                                v-model="relevanceFrom.sell_type"
                                style="width:100px"
                                @change="relevanceFromType"
                                filterable
                        >
                            <el-option
                                    v-for="item in relevance_list"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <span style="color: #888;">类型：</span>
                        <el-select
                                v-model="relevanceFrom.type"
                                style="width:100px"
                                filterable
                        >
                            <el-option
                                    v-for="item in relevance_type"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="name">
                        <el-input
                                v-model="relevanceFrom.name"
                                placeholder="请输入商品名称"
                                @keyup.enter.native="commodity"
                        ></el-input>
                    </el-form-item>
                    <el-form-item>
                        <dj-button size="small" @search="commodity">
                            <template #default>搜索</template>
                        </dj-button>
                    </el-form-item>
                </el-form>
                <el-table highlight-current-row :data="relevancelist" border size="mini" height="280px"  v-loading.body="listLoading">
                    <el-table-column align="center" label='序号' width="50">
                        <template slot-scope="scope">{{scope.$index+1+(currentPage-1)*20}}</template>
                    </el-table-column>
                    <el-table-column align="center" label="商品名称" prop="name"></el-table-column>
                    <el-table-column align="center" label="类型" prop="type_name"></el-table-column>
                    <el-table-column align="center" label="有效期" prop="time"></el-table-column>
                    <el-table-column align="center" label="更新时间" prop="update_time"></el-table-column>
                    <el-table-column align="center" label='操作'>
                        <template slot-scope="scope">
                            <el-button  type="primary" size="mini" @click="addRelevance(scope.row)" :disabled="isDisabled">添加</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="bottom_box">
                    <el-pagination
                            background
                            @current-change="relevanceCurrentChange"
                            :current-page.sync="relevancePage"
                            :page-size="20"
                            layout="prev, pager, next, jumper"
                            :page-count="relevanceTotal"
                            style="margin-top: 5px"
                    ></el-pagination>
                </div>
            </el-form>
            <div style="text-align:right;margin:20px 0 20px">
                <el-button v-show="!isDisabled" @click="saveClick" type="primary" size="small">保存</el-button>
            </div>
        </div>

        <!-- 弹框 -->
        <el-dialog  title="选择最多签到次数" :visible.sync="addTypeDialog" width="400px">
            <div class="main">
                <div v-for="(item,index) in dialoglist" :key="index" @click="addSelect(item)">{{item.lable}}</div>
            </div>
        </el-dialog>
        <!-- 自定义底部 -->
        <div class="bottom_box" v-if="tab_view==1">
            <el-pagination class="pull-left" background @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="20"
                           layout="prev, pager, next, jumper" :total="totalDataNumber">
            </el-pagination>
        </div>
    </div>
</template>
<script>
    import {
        getStore,
        goods_list,
        goods_page,
        getInfoPage,
        getInfo,
        signSave,
        signEnable,
        signDetails
    } from "@/api/operation/sign_package";
    import {
        notCharmap
    } from "@/utils/validate";
    import { getGoodsType } from '@/utils';
    export default {
        name: 'sign_package',
        data(){
            return{
                list: null,  //数据
                store_list:[],
                tab_view:1,
                top_title:"签到方案配置",
                listLoading: false,  //表格换场动画
                state_list:[{id:"-1",name:"全部"},{id:"0",name:"已停用"},{id:"1",name:"已启用"}],
                dialoglist:[{nums:1,lable:"一次"},{nums:2,lable:"二次"},{nums:3,lable:"三次"},{nums:4,lable:"四次"},{nums:5,lable:"五次"}],
                addTypeDialog: false, // 弹窗是否显示
                formInline: {  //开始时间，结束时间
                    store_id:"",
                    status:"-1",
                    name:"",
                },
                currentPage: 1,
                totalDataNumber: 0,
                distributionRadio:"",
                selectList:[],
                infoForm:{
                    name:"",
                    times:"",
                    store_id:"",
                    json_list:[],
                },
                isDisabled:false, //是否可更改
                distributionDate:"",//当前要被分销的数据
                relevancelist:[],
                relevancePage: 1,
                relevanceTotal: 0,
                relevance_list:[{ id: "", name: "全部" },{ id: "1", name: "优惠券" },{ id: "2", name: "商品" },],
                relevance_type:[],
                type_list1: [
                    { id: "0", name: "全部" },
                    { id: "2", name: "办卡" },
                    { id: "3", name: "充值" },
                    { id: "4", name: "续期" },
                    { id: "5", name: "门票" },
                    { id: "6", name: "企划" },
                    { id: "7", name: "实物" },
                ],
                con_type_list: [
                    { id: "1", name: "代金券" },
                ],
                relevanceFrom:{
                    //商品搜索
                    type:"",
                    name: "",
                    sell_type:"",
                    store_id:"",
                },
            }
        },
        mounted() {
            this.getstore();
        },
        methods:{
            getstore() {
                getStore({ category_id: 715 }).then((response) => {
                    this.store_list = response;
                    let store_id = this.$route.params.store_id?this.$route.params.store_id:this.$store.getters.optionId;
                    let data = response.filter(
                        res => res.id == store_id
                    );
                    if (data.length > 0) {
                        this.formInline.store_id = data[0].id;
                        this.relevanceFrom.store_id = data[0].id;
                    }
                    this.listArray();
                });
            },
            listArray(){  //获取数据
                this.listLoading = true;
                this.list = [];
                this.relevanceFrom.store_id = this.formInline.store_id;
                getInfoPage(this.formInline).then(response=>{
                    this.totalDataNumber = response.data.count / 1;
                    if (this.totalDataNumber == 0) {
                        this.listLoading = false;
                    } else {
                        getInfo(this.formInline).then(res=>{
                            this.list = res.data;
                            this.listLoading = false;
                        });
                    }
                });
            },
            handleCurrentChange(val) {  //获取某个分页的数据
                this.listLoading = true;
                getInfo(this.formInline,val).then(res=>{
                    this.list = res.data;
                    this.listLoading = false;
                }).catch(res => {
                    this.listLoading = false;
                });
            },
            saveClick(){
                let json_list=[];
                if(!notCharmap(this.infoForm.name)){
                    this.$message.error("请填写正确的方案名称");
                    return
                }
                for(let i=0;i<this.selectList.length;i++){
                    if(!("name" in this.selectList[i])){
                        this.$message.error(`请选择累计签到《${this.selectList[i].lable}》要关联的商品`);
                        return
                    }else{
                        json_list.push({
                            times:i+1,
                            goods_id:this.selectList[i].id
                        })
                    }
                }
                let data={
                    name:this.infoForm.name,
                    times:this.selectList.length,
                    store_id:this.formInline.store_id,
                    json_list:json_list,
                }
                // console.log(data);
                signSave(data).then(res=>{
                    if(res.code==1){
                        this.clearDate();
                        this.tab_view=1;
                        this.listArray();
                        this.$message.success(res.message);
                    }
                })
            },
            signEnables(row){
                if(row.status==1){
                    this.$confirm('是否确定停用该方案？', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(()=>{
                        signEnable({plan_id:row.id,status:"0",store_id:this.formInline.store_id}).then(res=>{
                            if(res.code==1){
                                this.$message.success(res.message);
                                this.listArray();
                            }
                        });
                    }).catch(() => {
                        row.status = true;
                    });
                }else{
                    signEnable({plan_id:row.id,status:"1",store_id:this.formInline.store_id}).then(res=>{
                        if(res.code==1){
                            this.$message.success(res.message);
                            this.listArray();
                        }
                    });
                }
            },
            details(row){
                this.commodity();
                signDetails({plan_id:row.id}).then(res=>{
                    if(res.code==1){
                        this.tab_view=2;
                        this.isDisabled=true;
                        this.distributionRadio="";
                        this.infoForm.name=row.name;
                        const data=this.getGoodsData(res.data);
                        for(let i=0;i<res.data.length;i++){
                            const obj={};
                            this.$set(this.selectList,i,Object.assign(obj,data[i],this.dialoglist[i]));
                        }
                    }
                });
            },
            addSelect(item){ //选择次数
                this.tab_view=2;
                this.selectList=[];
                this.addTypeDialog = false;
                for(let i=0;i<item.nums;i++){
                    this.selectList[i]=this.dialoglist[i];
                }
            },
            addRelevance(row){  //添加商品
                if(this.distributionRadio){
                    const obj={};
                    this.$set(this.selectList,(this.distributionRadio-1),Object.assign(obj,this.selectList[this.distributionRadio-1],row));
                }else{
                    this.$message.error("请先选择累计签到次数")
                }
            },
            delRelevance(index){ //移除商品
                this.$set(this.selectList,index,this.dialoglist[index]);
            },
            commodity(){
                this.listLoading = true;
                this.relevancelist = [];
                goods_page(this.relevanceFrom).then(response=>{
                    this.relevanceTotal = response.data.page / 1;
                    if (this.relevanceTotal == 0) {
                        this.listLoading = false;
                    } else {
                        goods_list(this.relevanceFrom).then(res=>{
                            this.relevancelist =  this.getGoodsData(res.data);
                            this.listLoading = false;
                        });
                    }
                });
            },
            getGoodsData(data) {
                data.forEach((val) => {
                    val.type_name = getGoodsType(val.type?val.type:val.second_type);
                    val.time =
                        val.chose_time_type == 1
                            ? val.effect_time.replace(/-/g, ".").replace(/,/g, "-")
                            : val.effect_time > 0
                            ? "购买后" + val.effect_time + "天内有效"
                            : "";
                    val.time = val.time
                        ? val.time
                        : val.effect_time === "0"
                            ? "购买后当天有效"
                            : "购买后立即生效";
                });
                return data;
            },
            relevanceCurrentChange(val){
                this.listLoading = true;
                goods_list(this.relevanceFrom,val).then(res=>{
                    this.relevancelist =  this.getGoodsData(res.data);
                    this.listLoading = false;
                });
            },
            relevanceFromType(){
                if(this.relevanceFrom.sell_type=="2"){
                    this.relevance_type=this.type_list1;
                    this.relevanceFrom.type='0';
                }else if(this.relevanceFrom.sell_type=="1"){
                    this.relevance_type=this.con_type_list;
                    this.relevanceFrom.type='1';
                }else{
                    this.relevanceFrom.type='';
                }
            },
            backClick() {  //详情里的返回按钮
                if (!this.isDisabled) {
                    this.$confirm(
                        "返回后已修改的数据不会保存，是否放弃本次操作？",
                        "提示",
                        {type: "warning"}
                    ).then(() => {
                        this.tab_view = 1;
                        this.clearDate();
                    });
                }else{
                    this.tab_view = 1;
                    this.clearDate();
                }
            },
            clearDate(){
                this.infoForm.name="";
                this.selectList=[];
                this.distributionRadio="";
            },
            addTypeClick() {
                this.isDisabled = false;
                this.addTypeDialog = true;
                this.commodity();
            },
            closeDialoig(){
                this.addTypeDialog = false;
            }
        }
    };
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
    .customContainer {
        overflow-y: auto;
    }
    .main{
        display: flex;
        flex-wrap: wrap;
        div{
            width: 100px;
            height: 100px;
            font-size: 20px;
            border: 1px solid #ccc;
            text-align: center;
            line-height: 100px;
            margin:10px;
        }
        div:hover{
            cursor: pointer;
            background: #36a3f7;
            color: white;
        }
    }
    .tab_title {
        width: 200px;
        font-size: 20px;
        font-weight: bold;
        margin: 5px 0 20px 70px;
    }
    .op_title {
        margin: 30px 0 20px;
        font-size: 16px;
        font-weight: bold;
        color: #282828;
        padding:0 0 10px 20px;
        box-sizing: border-box;
        border-bottom: 1px solid #dcdfe6;
    }
</style>
